/**
 * 解析目录结构字符串并生成相应的目录和文件
 * @version 1.2.0
 * @filename auto.mjs
 */
import fs from 'fs';
import path from 'path';

// 目录规划
let filePath = './_目录规划.md';
if (!fs.existsSync(filePath)) {
    console.log('[文件不存在]', filePath);
    process.exit();
}
let text = fs.readFileSync(filePath).toString(), keyword = '# 目录规划';
let pos = text.indexOf(keyword);
if (pos == -1) {
    console.log('[文件内容是空的]', filePath);
    process.exit();
}
text = text.substring(pos + keyword.length);

const dirRoot = '../', content = fs.readFileSync('./_template.md').toString();
let dirPath = dirRoot;
text.split("\n").forEach(str => {
    str = str.replace(/（.*）/ig, '').trim();
    if (str.startsWith('-')) {
        str = str.substring(1).trim();
    }
    if (str.length == 0) {
        return;
    }
    if (str.endsWith('.md')) {
        filePath = path.join(dirPath, str);
        if (fs.existsSync(filePath)) {
            console.log('[文件已存在]', filePath);
        } else {
            fs.writeFileSync(filePath, content.replaceAll('__title__', str.slice(str.indexOf('-') + 1, -3))).replaceAll('__date__', '');
            console.log('[创建文件]', filePath);
        }
        return;
    }
    dirPath = dirRoot + str;
    if (fs.existsSync(dirPath)) {
        console.log('[目录已存在]', dirPath);
    } else {
        fs.mkdirSync(dirPath);
        console.log('[创建目录]', dirPath);
    }
})
console.log('finish.');